package com.czy.owner.db;

import android.content.Context;

import com.czy.owner.entity.CarInfo;
import com.czy.owner.global.Constants;
import com.czy.owner.entity.ChainStoresModel;
import com.czy.owner.entity.OwnerInfoModel;
import com.czy.owner.entity.SessionInfoModel;
import com.czy.owner.entity.UserInfoModel;
import com.czy.owner.net.exception.RetryWhenNetworkException;
import com.czy.owner.net.utils.JsonUtil;
import com.czy.owner.utils.GsonUtils;
import com.czy.owner.utils.MD5;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.DbManager;
import org.xutils.ex.DbException;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by King on 2016/6/30 0030.
 */
public class UserHelper {
    private final String TAG = getClass().getSimpleName();
    private static UserHelper mInstance = null;
    private DbManager db = null;

    private String userAccount = null;
    private String userPassword = null;
    private String AUTH_KEY = null;         //MD5(UserName+APPName+UserPassword)
    private boolean isLogined = false;
    private UserTable mUser = null;
    private SessionInfoModel mSessionInfoModel = null;
    private UserInfoModel mUserInfoModel = null;
    private OwnerInfoModel mOwnerInfoModel = null;
    private List<ChainStoresModel> mChainStoresList = new ArrayList<>();
    private List<CarInfo> mCarInfoList = null;
    private int defaultCarIndex = 0;  // 默认车辆索引 无车辆时,为-1;

    private int selectStoreId = 0;
    private boolean isCloseMall = false;  // 所绑定门店是否关闭

    public static synchronized UserHelper getInstance() {
        if (mInstance == null) {
            mInstance = new UserHelper();
        }
        return mInstance;
    }

    public int getSelectStoreId() {
        return selectStoreId;
    }

    public void setSelectStoreId(Context mContext, int selectStoreId) {
        this.selectStoreId = selectStoreId;
        SharedPreferencesUtils.setParam(mContext, userAccount + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, selectStoreId);
    }


    public String getAuthKey() {
        return AUTH_KEY;
    }

    public String getAuthKeyFromStorage(Context mContext) {
        return (String) SharedPreferencesUtils.getParam(mContext, userAccount + Constants.SHARED_PREFERENCES_KEY_AUTH_KEY_STORAGE, "");
    }

    public void saveUserAuth(String userName, String userPassword) {
        saveUserAuth(userName, userPassword, false);
    }

    public void saveUserAuth(String userName, String userPassword, boolean isGenerateAuthKey) {
        if (db == null) {
            db = DbHelper.getInstance().getDb();
        }
        try {
            UserTable tmpUser = db.selector(UserTable.class).where("useraccount", "=", userName).findFirst();

            if (tmpUser == null) {
                UserTable user = new UserTable();
                user.setUserAccount(userName);
                user.setUserPassword(userPassword);
                user.setLastLoginTime(System.currentTimeMillis());
                db.saveOrUpdate(user);
            } else {
                tmpUser.setUserAccount(userName);
                tmpUser.setUserPassword(userPassword);
                tmpUser.setLastLoginTime(System.currentTimeMillis());
                db.update(tmpUser);
            }

        } catch (DbException e) {
            e.printStackTrace();
        }
        if (isGenerateAuthKey) {
            generateAuthKey(userName, userPassword);

        }
    }

    public UserTable getLastLoginUser() {
        if (db == null) {
            db = DbHelper.getInstance().getDb();
        }
        try {
            mUser = db.selector(UserTable.class).where("lastlogintime", ">", System.currentTimeMillis() - 7 * 24 * 3600 * 1000).orderBy("lastlogintime", true).findFirst();
        } catch (DbException e) {
            e.printStackTrace();
        }
        if (mUser != null) {
            userAccount = mUser.getUserAccount();
            userPassword = mUser.getUserPassword();
        }
        return mUser;
    }

    public void generateAuthKey(String userName, String userPassword) {
        this.userAccount = userName;
        this.userPassword = userPassword;
        AUTH_KEY = MD5.getMD5Str(userName + Constants.APP_PREF + userPassword);
    }

    public void saveUserInfo(Context mContext, String data) {
        if (AUTH_KEY == null) {
            MyLog.e(TAG, "Please execute the 'generateAuthKey' method before running this method!");
        }
        SharedPreferencesUtils.setParam(mContext, userAccount + Constants.SHARED_PREFERENCES_KEY_AUTH_KEY_STORAGE, AUTH_KEY);
        //session信息 sessionInfoModel
        String sessionInfo = JsonUtil.getJsonValuesString(data, "sessionInfo");
        SharedPreferencesUtils.setParam(mContext, AUTH_KEY + Constants.SHARED_PREFERENCES_KEY_SESSION_INFO_MODEL, sessionInfo);
        mSessionInfoModel = GsonUtils.getBean((String) SharedPreferencesUtils.getParam(mContext, AUTH_KEY + Constants.SHARED_PREFERENCES_KEY_SESSION_INFO_MODEL, ""), SessionInfoModel.class);
        mSessionInfoModel = GsonUtils.getBean(sessionInfo, SessionInfoModel.class);
        //用户信息 userInfoModel
        String userInfo = JsonUtil.getJsonValuesString(data, "userInfo");
        SharedPreferencesUtils.setParam(mContext, AUTH_KEY + Constants.SHARED_PREFERENCES_KEY_USER_INFO_MODEL, userInfo);
        mUserInfoModel = GsonUtils.getBean(userInfo, UserInfoModel.class);
        //车主信息 ownerInfoModel
        String ownerInfo = JsonUtil.getJsonValuesString(data, "ownerInfo");
        SharedPreferencesUtils.setParam(mContext, AUTH_KEY + Constants.SHARED_PREFERENCES_KEY_OWNER_INFO_MODEL, ownerInfo);
        mOwnerInfoModel = GsonUtils.getBean(ownerInfo, OwnerInfoModel.class);
        MyLog.e("yang","storeIdstoreIdstoreId=="+mOwnerInfoModel.getStoreId());
        //门店信息(连琐店信息)
        String chainStores = JsonUtil.getJsonValuesString(data, "chainStores");
        if (chainStores != null) {
            SharedPreferencesUtils.setParam(mContext, AUTH_KEY + Constants.SHARED_PREFERENCES_KEY_CHAIN_STORES_MODEL, chainStores);
            mChainStoresList = new Gson().fromJson(chainStores, new TypeToken<List<ChainStoresModel>>() {
            }.getType());
        }
        /*MyLog.i("King","sessionInfo:"+sessionInfo);
        MyLog.i("King","userInfo:"+userInfo);
        MyLog.i("King","ownerInfo:"+ownerInfo);*/
    }

    public void saveChainStores(Context mContext, String data) {
        if (AUTH_KEY == null) {
            MyLog.e(TAG, "Please execute the 'generateAuthKey' method before running this method!");
        }

        //门店信息(连琐店信息)
        String chainStores = JsonUtil.getJsonValuesString(data, "chainStores");
        if (chainStores != null) {
            SharedPreferencesUtils.setParam(mContext, AUTH_KEY + Constants.SHARED_PREFERENCES_KEY_CHAIN_STORES_MODEL, chainStores);
            mChainStoresList = new Gson().fromJson(chainStores, new TypeToken<List<ChainStoresModel>>() {
            }.getType());
        }

    }

    public boolean isLogined() {
        return isLogined;
    }

    public void setIsLogined(boolean b) {
        this.isLogined = b;
    }

    public SessionInfoModel getSessionInfoModel(Context mContext) {
        if (mSessionInfoModel == null) {
            if (AUTH_KEY == null) {
                getLastLoginUser();
                if (mUser == null) {
                    return null;
                }
                generateAuthKey(mUser.getUserAccount(), mUser.getUserPassword());
            }
            if (AUTH_KEY == null || !AUTH_KEY.equals(getAuthKeyFromStorage(mContext))) {
                return null;
            } else {
                mSessionInfoModel = GsonUtils.getBean((String) SharedPreferencesUtils.getParam(mContext, AUTH_KEY + Constants.SHARED_PREFERENCES_KEY_SESSION_INFO_MODEL, ""), SessionInfoModel.class);
                if (mSessionInfoModel == null) {
                    MyLog.i(TAG, "mSessionInfoModel is null:");
                }
            }
        }
        return mSessionInfoModel;
    }

    public String getSession(Context mContext) {
        if (isLogined() && getSessionInfoModel(mContext) != null) {
            return mSessionInfoModel.getSession();
        } else {
            return "";
        }
    }

    public void setSessionInfoModel(SessionInfoModel mSessionInfoModel) {
        this.mSessionInfoModel = mSessionInfoModel;
    }

    public void setSessionInfoModel(Context mContext, SessionInfoModel mSessionInfoModel) {
        this.mSessionInfoModel = mSessionInfoModel;
        SharedPreferencesUtils.setParam(mContext, AUTH_KEY + Constants.SHARED_PREFERENCES_KEY_SESSION_INFO_MODEL, GsonUtils.GsonToString(mSessionInfoModel));
    }

    public UserInfoModel getUserInfoModel(Context mContext) {
        if (mUserInfoModel == null) {
            if (AUTH_KEY == null) {
                getLastLoginUser();
                if (mUser == null) {
                    return null;
                }
                generateAuthKey(mUser.getUserAccount(), mUser.getUserPassword());
            }
            if (AUTH_KEY == null || !AUTH_KEY.equals(getAuthKeyFromStorage(mContext))) {
                return null;
            } else {
                mUserInfoModel = GsonUtils.getBean((String) SharedPreferencesUtils.getParam(mContext, AUTH_KEY + Constants.SHARED_PREFERENCES_KEY_USER_INFO_MODEL, ""), UserInfoModel.class);
                MyLog.i(TAG, "mUserInfoModel is null:");
            }
        }
        return mUserInfoModel;
    }

    public void setUserInfoModel(UserInfoModel mUserInfoModel) {
        this.mUserInfoModel = mUserInfoModel;
    }

    public void setUserInfoModel(Context mContext, UserInfoModel mUserInfoModel) {
        this.mUserInfoModel = mUserInfoModel;
        SharedPreferencesUtils.setParam(mContext, AUTH_KEY + Constants.SHARED_PREFERENCES_KEY_USER_INFO_MODEL, GsonUtils.GsonToString(mUserInfoModel));
    }

    public OwnerInfoModel getOwnerInfoModel(Context mContext) {
        if (mOwnerInfoModel == null) {
            if (AUTH_KEY == null) {
                getLastLoginUser();
                if (mUser == null) {
                    return null;
                }
                generateAuthKey(mUser.getUserAccount(), mUser.getUserPassword());
            }
            if (AUTH_KEY == null || !AUTH_KEY.equals(getAuthKeyFromStorage(mContext))) {
                return null;
            } else {
                mOwnerInfoModel = GsonUtils.getBean((String) SharedPreferencesUtils.getParam(mContext, AUTH_KEY + Constants.SHARED_PREFERENCES_KEY_OWNER_INFO_MODEL, ""), OwnerInfoModel.class);
                MyLog.i(TAG, "mOwnerInfoModel is null:");
            }
        }
        return mOwnerInfoModel;
    }

    public void setOwnerInfoModel(OwnerInfoModel mOwnerInfoModel) {
        this.mOwnerInfoModel = mOwnerInfoModel;
    }

    public void setOwnerInfoModel(Context mContext, OwnerInfoModel mOwnerInfoModel) {
        this.mOwnerInfoModel = mOwnerInfoModel;
        SharedPreferencesUtils.setParam(mContext, AUTH_KEY + Constants.SHARED_PREFERENCES_KEY_OWNER_INFO_MODEL, GsonUtils.GsonToString(mOwnerInfoModel));
    }

    public List<ChainStoresModel> getmChainStoresList(Context mContext) {
        if (mChainStoresList == null || mChainStoresList.size() == 0) {
            if (AUTH_KEY == null) {
                getLastLoginUser();
                if (mUser == null) {
                    return null;
                }
                generateAuthKey(mUser.getUserAccount(), mUser.getUserPassword());
            }
            if (AUTH_KEY == null || !AUTH_KEY.equals(getAuthKeyFromStorage(mContext))) {
                return null;
            } else {
                mChainStoresList = new Gson().fromJson((String) SharedPreferencesUtils.getParam(mContext, AUTH_KEY + Constants.SHARED_PREFERENCES_KEY_CHAIN_STORES_MODEL, ""), new TypeToken<List<ChainStoresModel>>() {
                }.getType());
                MyLog.i(TAG, "mChainStoresList is null:");
            }
        }
        return mChainStoresList;
    }

    public void setmChainStoresList(List<ChainStoresModel> mChainStoresList) {
        this.mChainStoresList = mChainStoresList;
    }

    public void setmChainStoresList(Context mContext, List<ChainStoresModel> mChainStoresList) {
        this.mChainStoresList = mChainStoresList;
        SharedPreferencesUtils.setParam(mContext, AUTH_KEY + Constants.SHARED_PREFERENCES_KEY_CHAIN_STORES_MODEL, GsonUtils.GsonToString(mChainStoresList));
    }

    public String getUserAccount() {
        if (userAccount == null) {
            getLastLoginUser();
        }
        return userAccount;
    }

    public void setUserAccount(String userAccount) {
        this.userAccount = userAccount;
    }

    public String getUserPassword() {
        if (userPassword == null) {
            getLastLoginUser();
        }
        return userPassword;
    }

    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }

    public String getAUTH_KEY() {
        return AUTH_KEY;
    }

    public void setAUTH_KEY(String AUTH_KEY) {
        this.AUTH_KEY = AUTH_KEY;
    }

    public List<CarInfo> getCarInfoList() {
        return mCarInfoList;
    }

    public void setCarInfoList(List<CarInfo> mCarInfoList) {
        this.mCarInfoList = mCarInfoList;
        if (mCarInfoList == null || mCarInfoList.size() == 0) {
            defaultCarIndex = -1;
        } else {
            defaultCarIndex = 0;
            for (int carIndex = 0; carIndex < mCarInfoList.size(); carIndex++) {
                if (mCarInfoList.get(carIndex).isDefault()) {
                    defaultCarIndex = carIndex;
                    break;
                }
            }
        }
    }

    public int getDefaultCarIndex() {
        return defaultCarIndex;
    }

    public void setDefaultCarIndex(int defaultCarIndex) {
        this.defaultCarIndex = defaultCarIndex;
    }

    public CarInfo getDefaultCar() {
        if (mCarInfoList == null || mCarInfoList.size() == 0 || defaultCarIndex == -1) {
            return null;
        }
        return mCarInfoList.get(defaultCarIndex);
    }

    public boolean isCloseMall() {
        return isCloseMall;
    }

    public void setCloseMall(boolean closeMall) {
        isCloseMall = closeMall;
    }
}
